import grails.util.GrailsNameUtils

import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.springframework.core.annotation.AnnotationUtils

includeTargets << grailsScript("_GrailsBootstrap")
includeTargets << grailsScript("_GrailsCreateArtifacts")


generateForName = null

target ('default': "Generates a  for a domain class") {
    depends(checkVersion, parseArguments, packageApp)
	
	
//    promptForName(type: "Domain Class")

    try {
        def name = argsMap["params"][0]
        if (!name || name == "*") {
            uberGenerate()
        }
        else {
            generateForName = name
            generateForOne()
        }
    }
    catch (Exception e) {
        logError("Error running The Generate generate", e)
        exit(1)
    }
}


target(generateForOne: "Generates controllers and views for only one domain class.") {
	depends(loadApp)

	def name = generateForName
	name = name.indexOf('.') > -1 ? name : GrailsNameUtils.getClassNameRepresentation(name)
	def domainClass = grailsApp.getDomainClass(name)

	if (!domainClass) {
		println "Domain class not found in grails-app/domain, trying hibernate mapped classes..."
		bootstrap()
		domainClass = grailsApp.getDomainClass(name)
	}

	if (domainClass) {
		generateForDomainClass(domainClass)
		event("StatusFinal", ["Finished generation for domain class ${domainClass.fullName}"])
	}
	else {
		event("StatusFinal", ["No domain class found for name ${name}. Please try again and enter a valid domain class name"])
		exit(1)
	}
}

target(uberGenerate: "Generates controllers and views for all domain classes.") {
	depends(loadApp)

	def domainClasses = grailsApp.domainClasses

	if (!domainClasses) {
		println "No domain classes found in grails-app/domain, trying hibernate mapped classes..."
		bootstrap()
		domainClasses = grailsApp.domainClasses
	}
	

	if (domainClasses) {
		domainClasses.each { domainClass -> generateForDomainClass(domainClass) }
		event("StatusFinal", ["Finished generation for domain classes"])
	}
	else {
		event("StatusFinal", ["No domain classes found"])
	}
}

def generateForDomainClass(domainClass) {
	
	def templateGenerator = classLoader.loadClass('com.ii2d.tg.TGGenerator').newInstance()
			
	//event("StatusUpdate", ["Generating views for domain class ${domainClass.fullName}"])
	templateGenerator.generate(domainClass, basedir)
	event("GenerateEnd", [domainClass.fullName])
}